// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq;

namespace SnapObjects.Data
{
    public interface IDataKeyFormater
    {
        string Format(DataKey key);
    }

    public class DataKey
    {
        private readonly NodeType _type;

        private readonly string _raw;
        private readonly DataKey[] _keys;
        private readonly (DataKey name, int index) _pair;

        private enum NodeType { Raw, Keys, Pair };

        public DataKey(string name)
        {
            _raw = name;

            _type = NodeType.Raw;
        }

        public DataKey(params DataKey[] key)
        {
            _keys = key;

            _type = NodeType.Keys;
        }

        public DataKey(DataKey name, int index)
        {
            _pair = (name, index);

            _type = NodeType.Pair;
        }

        public static implicit operator DataKey(string str)
        {
            return new DataKey(str);
        }

        public string ToTextString(
            string separator = ".",
            string indexLeft = "[",
            string indexRight = "]")
        {
            switch (_type)
            {
                case NodeType.Raw:
                    return _raw;

                case NodeType.Keys:
                    return String.Join(
                        separator,
                        _keys.Select(x => x.ToTextString(separator, indexLeft, indexRight)));

                case NodeType.Pair:
                    return $"{_pair.name.ToTextString(separator, indexLeft, indexRight)}"
                        + $"{indexLeft}{_pair.index}{indexRight}";

                default: return String.Empty;
            }
        }
    }
}
